package com.xuesi.demoadmin.service.impl;

import com.xuesi.demoadmin.entity.User;
import com.xuesi.demoadmin.service.ITokenService;
import com.xuesi.demoadmin.utils.TokenUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class TokenServiceImpl implements ITokenService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserServiceImpl userServiceImpl;

    @Override
    public User decode(String token) {
        Long userId = (Long) this.redisTemplate.opsForValue().get(token);
        return this.userServiceImpl.selectUserByUserId(userId);
    }

    @Override
    public String encode(Long userId) {
        String token = TokenUtils.getToken();
        try {
            this.redisTemplate.opsForValue().set(token, userId);
        } catch (Exception e) {
            return null;
        }
        return token;
    }
}
